#include "../include/threadsafe_queue.h"

#include <iostream>
#include <thread>
#include <chrono>
#include <vector>

threadsafe_queue<int> thq;
int data = 0;

void prepare() {
    for (int i = 0; i < 5; i++) {
        std::this_thread::sleep_for(std::chrono::seconds(1));
        thq.push(++data);
    }
}

void process() {
    for (int i = 0; i < 5; i++) {
        if (i & 1) {
            std::shared_ptr<int> value = thq.wait_and_pop();
            std::cout << *value << std::endl;
        }
        else {
            int value = -1;
            thq.wait_and_pop(value);
            std::cout << value << std::endl;
        }
    }
}

void add() {
    for (int i = 0; i < 100000; i++) {
        thq.push(i);
    }
}

int main(int argc, char* argv[]) {
    // 测试单线程功能
    threadsafe_queue<int> tq;
    tq.push(1);
    tq.push(2);
    tq.push(3);
    std::cout << tq.size() << std::endl;    // 3
    while (!tq.empty()) {
        std::cout << tq.front() << std::endl;
        tq.wait_and_pop();
    }   // 1 2 3

    tq.push(4);
    tq.push(5);

    std::cout << tq.front() << std::endl;   // 4
    std::cout << tq.back() << std::endl;    // 5

    threadsafe_queue<int> ttq(tq);

    if (tq == ttq) {
        std::cout << "equal" << std::endl;  // equal
    }

    // 测试多线程
    std::thread t1(process);
    std::thread t2(prepare);
    t1.join();
    t2.join();

    thq.clear();
    std::vector<std::thread> threads;
    for (int i = 0; i < 5; i++) threads.emplace_back(add);
    for (auto& thread : threads) thread.join();
    std::cout << thq.size() << std::endl;   // 500000
    thq.clear();

    if (!thq.try_pop()) {
        std::cout << "try_pop" << std::endl;    // try_pop
    }

    return 0;
}